package com.imchen.cms.cmscommon.utils;

import com.imchen.cms.exception.CmsException;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.util.ResourceUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;

/**
 * @author imchen
 * @create: 2019-01-26 16:32
 **/
public class FreeMarkerUtil {

    private static Configuration configuration = null;

    public static boolean generateHTML(String templateName, HashMap<String,Object> objMap, String savePath)  {
        boolean made = true;
        BufferedWriter out= null;
        if (configuration==null) {
            configuration = new Configuration(Configuration.VERSION_2_3_28);
        }
        try {
        configuration.setDirectoryForTemplateLoading(ResourceUtils.getFile("classpath:templates"));
        Template template=configuration.getTemplate(templateName);
        File htmlFile=new File(savePath);
        File parentDir = htmlFile.getParentFile();
        if (!parentDir.exists()){
           made=parentDir.mkdirs();
        }
        if (!made){
            throw new CmsException("create directory failed",500);
        }
        out=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFile), StandardCharsets.UTF_8));
            template.process(objMap,out);
        } catch (TemplateException | IOException | CmsException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}